using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using XYTerrain.Runtime;
using Debug = UnityEngine.Debug;

namespace XYTerrain.Editor
{
    public class TerrainEditorWindow : OdinEditorWindow
    {
        const int Group0 = 1;
        const int Group1 = 100;
        
        string controlTexName = "";
        
        bool isPaint;
        
        Texture[] brushTex;
        Texture[] texLayer;

        string brushFolder;
        
        int selBrush = 0;
        int selTex = 0;

        int brushSizeInPourcent;
        Texture2D MaskTex;
        
        public enum ControlTexSize
        {
            S128 = 0,
            S256,
            S512,
            S1024,
            S2048
        }





        string[] painterModeStr =
        {
            "默认方法", "新方案"
        };

        int painterModeId = 0;

        public PaintTerrainData paintData;



        List<string> layerMaskList = new List<string>();
        
        [MenuItem("Tools/TerrainEditor")]
        static void Open()
        {
            TerrainEditorWindow window = GetWindow<TerrainEditorWindow>();
            window.titleContent = new GUIContent("地形编辑工具");
            window.position = GUIHelper.GetEditorWindowRect().AlignCenter(360, 440);
        }
        
        [TabGroup("笔刷", Order = 0F)]
        [InfoBox("选中Scene内Obj，点笔刷按钮绘制，绘制完 “Ctrl+S”/按钮 保存。\nTips. 成功会输出 '保存成功' 字样。")]
        [CustomValueDrawer("Hide")]
        public bool Toggle;
        
        [TabGroup("笔刷")] [PropertyOrder(Group0 + 1)]
        [CustomValueDrawer("BtnOn")]
        public bool ButtonOn;

        [TabGroup("笔刷")] [PropertyOrder(Group0 + 3)] [PropertySpace(SpaceBefore = 2)] [Tooltip("根据滑条，调整笔刷大小。\n可通过快捷键 '+'/'-' 进行快捷调节。")]
        [LabelText("BrushSize")]
        [CustomValueDrawer("TheBrushSize")] 
        public float brushSize = 16f;
        
        [TabGroup("笔刷")] [PropertyOrder(Group0 + 3)] [Tooltip("根据滑条，调整笔刷强度。")]
        [LabelText("BrushStronger")]
        [CustomValueDrawer("TheBrushStronger")] 
        public float brushStronger = 0.5f;

        // v0.1.1
        [TabGroup("笔刷")] [PropertyOrder(Group0 + 3)] [Tooltip("根据选项，指定控制图的生成大小。")]
        [LabelText("ControlTextureSize")]
        public ControlTexSize controlTexSizeField;

        // v0.1.1
        [TabGroup("笔刷")] [PropertyOrder(Group0 + 4)] [Tooltip("选定所选Obj的LayMask进行笔刷。\n若所选和当前Obj的LayMask异同，则按钮进行同步。\n若有新增LayMask，则关闭工具界面再打开显示。")]
        [ValueDropdown("layerMaskList")]
        public string layerMask = "Default";
        
        // v0.1.1
        [TabGroup("笔刷")] [PropertyOrder(Group1 + 1)] [PropertySpace(SpaceBefore = 4)]
        [LabelText("绘制完保存")]
        [Button(30)]
        public void Save()
        {
            if (isPaint)
            {
                SaveTexture();
            }
        }

        [TabGroup("笔刷")] [PropertyOrder(Group1 + 2)] [PropertySpace(SpaceBefore = 4)]
        [CustomValueDrawer("BrushVarieties")]
        public string brush;

        [TabGroup("笔刷")] [PropertyOrder(Group1 + 3)] [PropertySpace(SpaceBefore = 4)]
        [CustomValueDrawer("TextureVarieties")]
        public string texture;

        
        [TabGroup("植被", Order = 1F)]
        public string tree;
        
        
        [TabGroup("细节", Order = 2F)]
        public string detail;

        protected override void OnEnable()
        {
            SceneView.duringSceneGui += OnSceneGUI;
            GetLayerMasks();
        }

        void OnDisable()
        {
            SceneView.duringSceneGui -= OnSceneGUI;
        }

        void OnSceneGUI(SceneView sceneView)
        {
            if (isPaint && Check())
            {
                GetIniBrush();


                switch (painterModeId)
                {
                   case 0 : GetLayerTex();  break;
                   case 1 : GetTerrainLayer(); break;
                }
                
                Painter();
            }
        }


        bool CheckShader(GameObject o)
        {
            var shaderName = o.GetComponent<MeshRenderer>().sharedMaterial.shader.name;
            return shaderName == "XinYuan/Nature/Terrain/MeshTerrain"|| shaderName == "XinYuan/Nature/Terrain/4Textures";
        }
    
        
        // 检查所选网格是否使用混合材质
        bool Check()
        {
            Transform CurrentSelect = Selection.activeTransform;
            
            bool Check = false;
            if (!isValidSelection(CurrentSelect))
            {
                // Debug.LogWarning("选择的模型无MeshRender或MeshFilter，请重选！");
                return false;
            }
            
            // 更新ShaderList
            if (CheckShader(CurrentSelect.gameObject))
            {
                Texture ControlTex = CurrentSelect.gameObject.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_Control");
                if (ControlTex == null) {
                    // Debug.LogError("当前模型材质求中未找到Control贴图,请创建！");
                    return false; }
                else {
                    Check = true; }
            }
            else {
                // Debug.LogError("不支持当前Shader！");
                return false; 
            }
            
            return Check;
        }
        
        // 创建Control贴图
        void createControlTex(int size, string ctrlTexPath = "Assets/")
        {
            Transform CurrentSelect = Selection.activeTransform;
            
            // 创建新Control贴图
            // 根据具体项目，配置文件存放路径
            Texture2D newMaskTex = new Texture2D(size, size, TextureFormat.RGBA32, true);
            Color[] colorbBase = new Color[size * size];
            for (int t = 0; t < colorbBase.Length; t++)
            {
                colorbBase[t] = new Color(1, 0, 0, 0);
            }
            newMaskTex.SetPixels(colorbBase);
            
            // 判断重命名
            bool exporNameSuccess = true;
            for (int num = 1; exporNameSuccess; num++)
            {
                string Next = CurrentSelect.name + "_ctrl" + num;
                if (!File.Exists(ctrlTexPath + CurrentSelect.name + "_ctrl" + ".png"))
                {
                    controlTexName = CurrentSelect.name;
                    exporNameSuccess = false;
                }
                else if (!File.Exists(ctrlTexPath + Next + ".png"))
                {
                    controlTexName = Next;
                    exporNameSuccess = false;
                }
            }

            string path = ctrlTexPath + controlTexName + ".png";
            byte[] bytes = newMaskTex.EncodeToPNG();
            // 保存
            File.WriteAllBytes(path, bytes);
            
            // Control贴图导入与设置   
            AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            TextureImporter textureIm = AssetImporter.GetAtPath(path) as TextureImporter;
            if (textureIm != null)
            {
                // textureIm.textureFormat = TextureImporterFormat.RGBA32;
                textureIm.textureCompression = TextureImporterCompression.Uncompressed;
                textureIm.isReadable = true;
                textureIm.anisoLevel = 9;
                textureIm.mipmapEnabled = false;
                textureIm.wrapMode = TextureWrapMode.Clamp;
                // v0.1.0
                textureIm.sRGBTexture = false;
            }

            AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            
            setControlTex(path);
        }
        
        // 设置Control贴图
        void setControlTex(string path)
        {
            // Transform CurrentSelect = Selection.activeTransform;
            
            Texture2D ControlTex = (Texture2D) AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
            Selection.activeTransform.gameObject.GetComponent<MeshRenderer>().sharedMaterial.SetTexture("_Control", ControlTex);
        }
        
        // 获取笔刷
        void GetIniBrush()
        {
            ArrayList BrushList = new ArrayList();
            Texture BrushesTL;
            
            var scriptOkb = MonoScript.FromScriptableObject(this);
            var path = AssetDatabase.GetAssetPath(scriptOkb);
            int lastIdx = path.LastIndexOf("/");
            string BrushPath = path.Substring(0, lastIdx) + "/Brushes";

            if (Directory.Exists(BrushPath))
            {
                DirectoryInfo direction = new DirectoryInfo(BrushPath);
                FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
                BrushList.Clear();
                foreach (var file in files)
                {
                    if (!file.Name.EndsWith(".png")) continue;
            
                    string fileName = file.Name;
                    BrushesTL = (Texture) AssetDatabase.LoadAssetAtPath(BrushPath + "/" + fileName, typeof(Texture));
            
                    BrushList.Add(BrushesTL);
                }
            }
            
            if (brushFolder != null)
            {
                BrushPath = brushFolder;
            
                if (Directory.Exists(BrushPath))
                {
                    DirectoryInfo direction = new DirectoryInfo(BrushPath);
                    FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
                    BrushList.Clear();
                    foreach (var file in files)
                    {
                        if (!file.Name.EndsWith(".png")) continue;
            
                        string fileName = file.Name;
                        BrushesTL = (Texture) AssetDatabase.LoadAssetAtPath(BrushPath + "/" + fileName, typeof(Texture));
            
                        BrushList.Add(BrushesTL);
                    }
                }
            }
            
            if (BrushList.Count == 0)
            {
                Debug.LogError("无有效笔刷");
            }
            
            brushTex = BrushList.ToArray(typeof(Texture)) as Texture[];
        }

        // v0.1.1_获取自定义笔刷列表文件夹
        void GetBrushFolder()
        {
            string Folder = EditorUtility.OpenFolderPanel("选择目录", "Assets", "");
            if (string.IsNullOrEmpty(Folder))
            {
                GUIUtility.ExitGUI();
                return;
            }
            
            string projectPath = FileUtil.GetProjectRelativePath(Folder);
            if (!AssetDatabase.IsValidFolder(projectPath))
            {
                EditorUtility.DisplayDialog("错误", "笔刷列表文件夹只可以选择工程内的文件夹目录（将外部笔刷列表文件夹复制到项目 /Assets/ 内）", "知道了!");
                GUIUtility.ExitGUI();
                return;
            }
            
            brushFolder = Folder.Substring(Folder.IndexOf("Assets"));
            
            GUIUtility.ExitGUI();
            
            Transform CurrentSelect = Selection.activeTransform;
            var childTran = CurrentSelect.GetComponentsInChildren<Transform>();
            int[] layers = new int[childTran.Length];
        }

        // 获取材质球中贴图
        void GetLayerTex()
        {
            Transform CurrentSelect = Selection.activeTransform;

            if (isValidSelection(CurrentSelect))
            {
                texLayer = new Texture[4];
                texLayer[0] = AssetPreview.GetAssetPreview(CurrentSelect.gameObject.GetComponent<MeshRenderer>()
                    .sharedMaterial.GetTexture("_Splat0")) as Texture;
                texLayer[1] = AssetPreview.GetAssetPreview(CurrentSelect.gameObject.GetComponent<MeshRenderer>()
                    .sharedMaterial.GetTexture("_Splat1")) as Texture;
                texLayer[2] = AssetPreview.GetAssetPreview(CurrentSelect.gameObject.GetComponent<MeshRenderer>()
                    .sharedMaterial.GetTexture("_Splat2")) as Texture;
                texLayer[3] = AssetPreview.GetAssetPreview(CurrentSelect.gameObject.GetComponent<MeshRenderer>()
                    .sharedMaterial.GetTexture("_Splat3")) as Texture;
            }
        }
        
       
        
        
        
        // v0.1.1_获取当前LayerMasks
        void GetLayerMasks()
        {
            for (int i=0; i<=30; i++ )
            {
                if (LayerMask.LayerToName(i) == "") continue;
            
                layerMaskList.Add(LayerMask.LayerToName(i));
            }
        }
        
        void Painter()
        {
            Transform CurrentSelect = Selection.activeTransform;
            
            // 获取当前模型MeshFilter
            MeshFilter temp = CurrentSelect.GetComponent<MeshFilter>();
            // 笔刷在模型上的正交大小
            float orthographicSize = (brushSize * CurrentSelect.localScale.x) * (temp.sharedMesh.bounds.size.x / 200);
            // 从材质球中获取Control贴图
            MaskTex = (Texture2D)CurrentSelect.gameObject.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_Control");
            
            // 笔刷在模型上的大小
            brushSizeInPourcent = (int)Mathf.Round((brushSize * MaskTex.width) / 100);
            // 检测输入
            Event e = Event.current;
            HandleUtility.AddDefaultControl(0);
            RaycastHit raycastHit = new RaycastHit();
            // 从鼠标位置发射一条射线
            Ray terrain = HandleUtility.GUIPointToWorldRay(e.mousePosition);
            //射线检测名为"Terrain"的层（要添加Layer的Terrain层）
            if (Physics.Raycast(terrain, out raycastHit, Mathf.Infinity, 1 << LayerMask.NameToLayer(layerMask)))
            {
                // 颜色
                Handles.color = Color.gray;
                // 根据笔刷大小在鼠标位置显示一个圆
                Handles.DrawWireDisc(raycastHit.point, raycastHit.normal, orthographicSize);
                
                // v0.1.1 快捷键调整笔刷大小，快捷保存
                if (e.type == EventType.KeyDown)
                {
                    if (e.keyCode == KeyCode.Equals)
                    {
                        brushSize += 1;
                    }
                    else if (e.keyCode == KeyCode.Minus)
                    {
                        brushSize -= 1;
                    }
                    else
                    {
                        bool eventDown = (e.modifiers & EventModifiers.Control) != 0;
                        if (!eventDown) return;

                        if (e.keyCode == KeyCode.S)
                        {
                            SaveTexture();
                        }
                    }
                }
                
                // 鼠标点击或按下并拖动进行绘制
                if ((e.type == EventType.MouseDrag && e.alt == false && e.control == false && e.shift == false && e.button == 0)
                    || (e.type == EventType.MouseDown && e.alt == false && e.control == false && e.shift == false  && e.button == 0))
                {
                    // 选择绘制的通道
                    Color targetColor = new Color(1f, 0f, 0f, 0f);
                    switch (selTex)
                    {
                        case 0:
                            targetColor = new Color(1f, 0f, 0f, 0f);
                            break;
                        case 1:
                            targetColor = new Color(0f, 1f, 0f, 0f);
                            break;
                        case 2:
                            targetColor = new Color(0f, 0f, 1f, 0f);
                            break;
                        case 3:
                            targetColor = new Color(0f, 0f, 0f, 1f);
                            break;
                    }

                    Vector2 pixelUV = raycastHit.textureCoord;
                    
                    // 计算笔刷所覆盖的区域
                    int PuX = Mathf.FloorToInt(pixelUV.x * MaskTex.width);
                    int PuY = Mathf.FloorToInt(pixelUV.y * MaskTex.height);
                    int x = Mathf.Clamp(PuX - brushSizeInPourcent / 2, 0, MaskTex.width - 1);
                    int y = Mathf.Clamp(PuY - brushSizeInPourcent / 2, 0, MaskTex.height - 1);
                    int width = Mathf.Clamp((PuX + brushSizeInPourcent / 2), 0, MaskTex.width) - x;
                    int height = Mathf.Clamp((PuY + brushSizeInPourcent / 2), 0, MaskTex.height) - y;
                    
                    // 获取Control贴图被笔刷所覆盖的区域的颜色
                    Color[] terrainBay = MaskTex.GetPixels(x, y, width, height, 0);
                    
                    // 获取笔刷形状状贴图 
                    Texture2D TBrush = brushTex[selBrush] as Texture2D;
                    
                    // 笔刷透明度
                    float[] brushAlpha = new float[brushSizeInPourcent * brushSizeInPourcent];

                    // 根据笔刷贴图计算笔刷的透明度
                    for (int i = 0; i < brushSizeInPourcent; i++)
                    {
                        for (int j = 0; j < brushSizeInPourcent; j++)
                        {
                            brushAlpha[j * brushSizeInPourcent + i] = TBrush
                                .GetPixelBilinear(((float) i) / brushSizeInPourcent, ((float) j) / brushSizeInPourcent)
                                .r;
                        }
                    }
                    
                    // 计算绘制后的颜色
                    for (int i = 0; i < height; i++)
                    {
                        for (int j = 0; j < width; j++)
                        {
                            int index = (i * width) + j;
                            float Stronger = brushAlpha[
                                    Mathf.Clamp((y + i) - (PuY - brushSizeInPourcent / 2), 0, brushSizeInPourcent - 1) *
                                    brushSizeInPourcent + Mathf.Clamp((x + j) - (PuX - brushSizeInPourcent / 2), 0,
                                        brushSizeInPourcent - 1)] * brushStronger;

                            terrainBay[index] = Color.Lerp(terrainBay[index], targetColor, Stronger);
                        }
                    }
                    // 保存历史记录以便撤销
                    Undo.RegisterCompleteObjectUndo(MaskTex, "meshPaint");
                    
                    // 把绘制后的Control贴图保存起来
                    MaskTex.SetPixels(x, y, width, height, terrainBay, 0);
                    MaskTex.Apply();
                }
                // else if (e.type == EventType.MouseUp && e.alt == false && e.button == 0)
                // {
                //     SaveTexture();
                // }
            }
        }
        
        public void SaveTexture()
        {
            var path = AssetDatabase.GetAssetPath(MaskTex);

            if (path == "")
            {
                Debug.LogWarning("当前选项为空，保存失败。");
                return;
            }
            
            var bytes = MaskTex.EncodeToPNG();
            File.WriteAllBytes(path, bytes);
            AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);//刷新
            
            Debug.Log("保存成功");
        }

        bool isValidSelection(Transform trans)
        {
            Transform CurrentSelect = Selection.activeTransform;
            
            if (trans == null)
                return false;
            MeshFilter filter;
            MeshRenderer renderer;
            bool isValid = true;
            isValid &= trans.TryGetComponent<MeshFilter>(out filter);
            isValid &= CurrentSelect.gameObject.TryGetComponent<MeshRenderer>(out renderer);
            return isValid;
        }
        
        bool BtnOn(bool value)
        {
            GUIStyle boolBtnOn = new GUIStyle(GUI.skin.GetStyle("Button"));
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            isPaint = GUILayout.Toggle(isPaint,
                EditorGUIUtility.IconContent("d_TerrainInspector.TerrainToolSplat On"), boolBtnOn,
                GUILayout.Width(35), GUILayout.Height(25));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            return value;
        }
        
        bool Hide(bool value)
        {
            GUILayout.BeginHorizontal();
            GUILayout.EndHorizontal();
            
            return value;
        }
        
        private float TheBrushSize(float value, GUIContent label)
        {
            return EditorGUILayout.Slider(label, value, 0f, 40f);
        }
        
        private float TheBrushStronger(float value, GUIContent label)
        {
            return EditorGUILayout.Slider(label, value, 0f, 1f);
        }
        
        string BrushVarieties(string value)
        {
            GetIniBrush();
            
            GUILayout.BeginVertical("Box");
            
            GUILayout.BeginHorizontal();
            GUILayout.Label("BrushVarieties");
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("自定义笔刷列表"))
            {
                GetBrushFolder();
            }
            GUILayout.EndHorizontal();
            
            GUILayout.BeginHorizontal("Box");
            selBrush = GUILayout.SelectionGrid(selBrush, brushTex, 6, "gridlist", 
                GUILayout.MinWidth(200), GUILayout.Height(50));
            GUILayout.EndHorizontal();
            
            GUILayout.EndVertical();
            
            return value;
        }
        
        string TextureVarieties(string value)
        {
            Transform CurrentSelect = Selection.activeTransform;

            int width = 2;


            painterModeId = GUILayout.Toolbar(painterModeId, painterModeStr);
            EditorGUILayout.Space(5);
            GUILayout.BeginVertical("Box");
            
            GUILayout.BeginHorizontal();
            GUILayout.Label("TextureVarieties");
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("创建ControlText"))
            {
                ControlTexSize texSize = controlTexSizeField;
                // ControlTexSize texSize = ControlTexSize.S128;
                int size = 1 << (int) texSize + 7;
                
                createControlTex(size);
            }
            if (GUILayout.Button("同步LayerMask"))
            {
                CurrentSelect.gameObject.layer = LayerMask.NameToLayer(layerMask);
            }
            GUILayout.EndHorizontal();
            
            if (CurrentSelect == null 
                || !isValidSelection(CurrentSelect))
            {
                EditorGUILayout.Space(width);
                EditorGUILayout.HelpBox("选择的模型无 ‘MeshRender’ 或 ‘MeshFilter’ ，请重选！", MessageType.Warning);
            }
            else if (CurrentSelect.gameObject.GetComponent<MeshRenderer>().sharedMaterial.shader != Shader.Find("XinYuan/Nature/Terrain/4Textures")&&
                     CurrentSelect.gameObject.GetComponent<MeshRenderer>().sharedMaterial.shader != Shader.Find("XinYuan/Nature/Terrain/MeshTerrain")
                     )
            {
                EditorGUILayout.Space(width);
                EditorGUILayout.HelpBox("不支持当前Shader，请更改！", MessageType.Warning);
            }
            else if (CurrentSelect.gameObject.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_Control") == null)
            {
                EditorGUILayout.Space(width);
                EditorGUILayout.HelpBox("当前模型材质球中未找到ControlTexture，请点击创建！", MessageType.Warning);
            }
            else if (LayerMask.LayerToName(CurrentSelect.gameObject.layer) != layerMask)
            {
                EditorGUILayout.Space(width);
                EditorGUILayout.HelpBox("当前模型LayerMask不是面板上指定LayerMask ，请点击同步！", MessageType.Warning);
            }
            else
            {
                switch ( painterModeId)
                {
                   case  0 : DrawOriginLayerGUI(); break;
                   case  1 : DrawTerrainLayerGUI(); break;
                }
            }
            
            GUILayout.EndVertical();
            
            return value;
        }

        private void DrawOriginLayerGUI()
        {
            GetLayerTex();
            
            GUILayout.BeginHorizontal("Box");
            selTex = GUILayout.SelectionGrid(selTex, texLayer, 4, "gridlist", 
                GUILayout.MinWidth(200), GUILayout.Height(80));
            GUILayout.EndHorizontal();
        }
        
        
        //------------------------------------------------------------------ 
        
        // Add

        
        
        // --------------  Add by zhicheng  使用TerrainLayer方法来管理贴图

        private GameObject cacheObject = null; 
        bool GetTerrainLayer()
        {

            if (Selection.activeObject != cacheObject)
            {
                Debug.Log("目标更变");
                paintData = null;
                cacheObject = Selection.activeObject as GameObject;
            }
            
            if (paintData==null)
            {
                paintData = (Selection.activeObject as GameObject)?.GetComponent<PaintTerrainData>();
                if (paintData == null)
                {
                   var creat =  EditorUtility.DisplayDialog("提示", "当前物体未生成Layer数据。\n是否进行生成?\n选择否将取消生成且切换回默认模式", "是", "否");
                   if (creat)
                   {
                       paintData = (Selection.activeObject as GameObject)?.AddComponent<PaintTerrainData>();
                   }
                   else
                   {
                       painterModeId = 0;
                       this.Repaint();
                       return false;
                   }

                }
            }
            OnTerrainLayerChange();
            
            return true;
        }

        private void OnTerrainLayerChange()
        {
            texLayer = new Texture[paintData.Layers.Count+1];

            string splat = "_Splat";
            string normal = "_Normal";
            string normalIntensity = "_NormalIntensity";
            string smoothness = "_Smoothness";
            var mat = paintData.gameObject.GetComponent<Renderer>().sharedMaterial;
            texLayer[0] = mat.GetTexture(splat + 0);
            for (int i = 0; i < 3; i++)
            {
               int matId = i + 1; 
                if (i < paintData.Layers.Count)
                {
                   texLayer[matId]  = AssetPreview.GetAssetPreview(paintData.Layers[i].diffuseTexture);
                   mat.SetTexture(splat+matId,paintData.Layers[i].diffuseTexture);
                   mat.SetTexture(normal+matId,paintData.Layers[i].normalMapTexture);
                   mat.SetFloat(normalIntensity+matId,paintData.Layers[i].normalScale);
                   mat.SetFloat(smoothness+matId,paintData.Layers[i].smoothness);
                   
                }
                else
                {
                    mat.SetTexture(splat+matId,null);
                    mat.SetTexture(normal+matId,null);
                }
               
            }
            
            
            
        }



        private int pickId;
        private int removeId;
        private void DrawTerrainLayerGUI()
        {
           
            // EditorGUILayout. 
            if (!GetTerrainLayer()) return;
            
            GUILayout.BeginHorizontal("Box");
            
            selTex = GUILayout.SelectionGrid(selTex, texLayer, texLayer.Length, "gridlist", 
                GUILayout.Width(80*texLayer.Length), GUILayout.Height(90));
            GUILayout.EndHorizontal();
            
            GUILayout.BeginHorizontal();
            if (paintData.Layers.Count < 3)
            {
                if (GUILayout.Button(" 添加图层",GUILayout.MaxWidth(100)))
                {
                    pickId = EditorGUIUtility.GetControlID(FocusType.Passive)+100;
                    EditorGUIUtility.ShowObjectPicker<TerrainLayer>(null,true,"",pickId);
                    OnBeginGUI += WaitSelectGameobject;
                    
                }    
            }

            if (paintData.Layers.Count > 0)
            {
                if (GUILayout.Button("移除图层",GUILayout.MaxWidth(100)))
                {
                    paintData.Layers.RemoveAt(selTex-1);
                    OnTerrainLayerChange();
                    // pickId = EditorGUIUtility.GetControlID(FocusType.Passive)+100;

                    // var options = new  GUIContent[paintData.Layers.Count];
                    //
                    // for (int i = 0; i < options.Length; i++)
                    // {
                    //     options[i] = new GUIContent(paintData.Layers[i].name);
                    // }

                    // EditorUtility.DisplayCustomMenu(EditorGUILayout.GetControlRect(),options,removeId, (x, y, z) =>
                    // {
                    //     paintData.Layers.RemoveAt(z);
                    //     OnTerrainLayerChange();
                    //     
                    // },null);
                }

                if (selTex - 1 >= 0)
                {
                    if(GUILayout.Button("定位图层",GUILayout.MaxWidth(100)))
                    {
                       Selection.activeObject =  paintData.Layers[selTex - 1];
                    }    
                }
                
            }
            
            
            
             
            GUILayout.EndHorizontal();

        }


        private void Remove()
        {
            
        }

        void WaitSelectGameobject()
        {
            if (Event.current is {commandName: "ObjectSelectorClosed"} && EditorGUIUtility.GetObjectPickerControlID() ==pickId  )
            {
                var o = (EditorGUIUtility.GetObjectPickerObject() as TerrainLayer);
                if (o != null) Debug.Log(o.name);
                pickId = -1;
                OnBeginGUI -= WaitSelectGameobject;
                if (o == null) return;
                
                
                paintData.Layers.Add(o);
                OnTerrainLayerChange();
            }

        }
        
        //------------------------------------------------------------------
        
        
    }
    
}
